import { useEffect, useState } from "react";
import { Image, List, Popup } from "antd-mobile";
import { staticImg } from "@/config";
import "./index.scss";
// import { t } from "@/utils";
import { CloseOutline } from "antd-mobile-icons";
import qs from "qs";
import { t } from "@/lang";
const query: Record<string, any> = qs.parse(location.search.slice(1));
const {
  sn,
  serialNo
} = query;
const newSn = sn || serialNo;
interface Props {
  deviceList: DeviceInfo[];
  onChangeSn: (sn: string) => void;
}
const Com = (props: Props) => {
  const [visible, setVisible] = useState(false);
  const [activeDevice, setActiveDevice] = useState<DeviceInfo>();
  props.deviceList.find(item => item.device_sn === newSn);
  useEffect(() => {
    setActiveDevice(props.deviceList.find(item => item.device_sn === newSn) || props.deviceList[0]);
  }, []);
  const showDeviceList = () => {
    setVisible(true);
  };
  const changeDeice = (device: DeviceInfo) => {
    console.log(device);
    props.onChangeSn(device.device_sn);
    setActiveDevice(device);
    setVisible(false);
  };
  const getActveDays = (() => {
    console.log(activeDevice?.create_time);
    if (activeDevice) {
      const date = activeDevice.create_time * 1000;
      const now = Date.now();
      const diff = now - date;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      return days;
    } else {
      return "-";
    }
  })();
  return <div id="deviceList">
    <List.Item prefix={<Image src={`${staticImg}/vip_pay/device.png`} />} onClick={showDeviceList}>
      <div className="device_info">
        <div className="title">{activeDevice?.device_name}</div>
        <div className="sn">{activeDevice?.device_sn}</div>
        <div className="create_date">{t("au.a_12")}{getActveDays}{t("au.a_13")}</div>
      </div>
    </List.Item>
    <Popup getContainer={null} bodyClassName="device_popup" visible={visible}>
      <header className="flex-between">
        <p></p>
        <p>{t("au.a_14")}</p>
        <CloseOutline fontSize={16} className="close_icon" onClick={() => setVisible(false)} />
      </header>
      <main>
        <List style={{
          maxHeight: "80vh",
          overflowY: "auto"
        }}>
          {props.deviceList?.map(item => <List.Item arrow={<Image width={15} src={activeDevice?.id === item.id ? `${staticImg}/vip_pay/checked.png` : `${staticImg}/vip_pay/unchecked.png`} />} key={item.id} prefix={<Image src={`${staticImg}/vip_pay/device.png`} />} onClick={() => changeDeice(item)}>
            <div className="device_info">
              <div className="title">{item.device_name}</div>
              <div className="sn">{item.device_sn}</div>
            </div>
          </List.Item>)}
        </List>
      </main>
    </Popup>
  </div>;
};
export default Com;